<?php
/**
 * @file functions.php
 * @package taobaoke
 * @subpackage 
 * @version $id: 0.1 UTF-8 2009-7-10 下午07:32:24 $
 * @author LD King (mifunny.info)
 * @copyright Copyright (c) 2007 - 2009 MiFunny China Inc. (http://mifunny.info)
 * 主要数据处理函数
 */

require_once 'itemGet.php';
require_once 'db.class.php';

/**
 * 通过修改过得xmlrpc.php发布文章
 *
 * @param Array $item
 * @return bool
 */
function postItem2XMLRPC($post){
	//$post = makeItem2Post($item);
	require_once 'xmlrpc/xmlrpc.inc';
	$rpc = new xmlrpc_client(XMLRPC_PATH);
	
	$post['tags_input'] = implode( ',' ,$post['tags_input'] );
	
	if ( !empty($post['post_meta']) ){
		$post['custom_fields'] = array( array('key' => 'pic_url', 'value' => $post['post_meta']['pic_url']),
										array('key' => 'price', 'value' => $post['post_meta']['price'])
									);
		unset( $post['post_meta'] );
	}
	
	$post['dateCreated'] = date('Ymd\TH:i:s', $post['post_date']);
	$post['dateCreated'] = new xmlrpcval($post['dateCreated'], 'dateTime.iso8601');
	unset( $post['post_date'] );
	
	$x = new xmlrpcmsg("metaWeblog.newPost",
	                     array(php_xmlrpc_encode("1"),
	                        php_xmlrpc_encode("green"),
	                        php_xmlrpc_encode("qq567890"),
	                        php_xmlrpc_encode($post),
	                        php_xmlrpc_encode("1"))
	                    );
	                    
	$rpc->return_type = 'phpvals';
	$re =$rpc->send($x);
	
	//print_r($re);
	if ($re->errno=="0") return $re->val;
	else return 0;
} //END func postItem2XMLRPC

/**
 * 通过WordPress自身的程序插入文章(速度较慢，但数据库准确)
 *
 * @param Array $item
 * @return Array
 */
function postItem2WP($item){
//	echo "BABY";
//	include '/home/http/7heart/wp-config.php';
//	echo "BABY";
	$post = makeItem2Post($item);
	$delicious = array('iid' => $post['item_iid'],
						'title' => $post['post_title'],
						'desc' => $post['post_excerpt'],
						'tags' => implode(' ',$post['tags_input']),
						'content' => $post['post_content'] 
				);
	$post['tags_input'] = implode(',',$post['tags_input']);
	$post['post_date'] = date("Y-m-d H:i:s", $post['post_date'] );
	
	$ID = wp_insert_post($post); //发布文章，得到ID号
	foreach ($post['post_meta'] as $k => $v) { //添加自定义字段
		delete_post_meta($ID, $k);
		add_post_meta($ID, $k, $v, true) or update_post_meta($ID, $k, $v);
	}
	
	$delicious['wp_id'] = $ID;
	$delicious['url'] = get_permalink($ID); //得到文章URL
	
	if ($ID) return $delicious;
	else return false;	
}//END func postItem2WP

/**
 * 把从数据库中得到的商品原信息转换成POST信息
 *
 * @param Array $item
 * @return Array
 */
function makeItem2Post($item, $m = true){
	//确定分类 和 自定义字段
global $CATEGORY_YID, $CATEGORY_HID, $AUTHORS;
$postCategory = array( $CATEGORY_YID, (int)$item['sid'] );
$postMeta = array();
if ( (int)$item['commission_num'] > 0 or $item['is'] == '2' ) {
	array_push($postCategory, $CATEGORY_HID);
	$postMeta['pic_url'] = $item['pic_url'];
	$postMeta['price'] = $item['price'];
}
//array_push($postCategory ,$CATEGORY_YID);

//作者
$postAuther = $AUTHORS[array_rand($AUTHORS)];

//时间
if( $m ){
		$postData = mktime() + mt_rand(0,750)*10800;
}else{
	$postData = mktime() - mt_rand(0,250)*10800;
}
//$postData = date("Y-m-d H:i:s", $randomPostTime );

//摘要
$postExceprt = getExcerpt($item['title2'], $item['price'], $item['desc']);

//关键字
$postTags = getKeywords($item['title'], $item['properties'], $item['cname']);

//缩略名 array ("(", ")", "[", "]", "?", ".", ",", "|", "\$", "*", "+", "^", "{", "}" );
$name = preg_replace('/\s|\.|\/|－/', '-', change2pinyin($postTags[0]));
$postName = urlencode( $name );

//内容
$postContent = getContent($item, $postTags);

$post = array(
	'comment_status' => 'open', // 'closed' means no comments.
	'ping_status' => 'closed', //Ping status?
	'post_author' => $postAuther,
	'post_category' => $postCategory,
	'post_content' =>  $postContent,
	'post_date' => $postData,
	'post_excerpt' => $postExceprt,
	'post_name' => $postName,
	'post_status' => 'publish',
	'post_title' => $item['title2'],
	'post_type' => 'post',
	'tags_input' => $postTags,
	'post_meta' => $postMeta,
	'item_iid' => $item['iid']
	);
	
	return $post;
}//END func makeItem2Post

/**
 * 更新所有规则
 */
function refurbishRules(){
	$ig = new tbkDB();
	$cats = $ig->getCatInfo();
	
	foreach ($cats as $cat){
		$ig->inRuleCat($cat['rid'],$cat['cid']);
	}
}//END func refurbishRules

/**
 * 获得淘宝分类,并更新数据库
 *
 * @param String $session
 * @return null
 */
function refurbishTaobaoCats($session, $parent_cid = '0'){
	$params = array(  
       'method' => 'taobao.itemcats.get.v2',
       'session'=> $session,
		'fields' => 'cid,parent_cid,name,is_parent,status,sort_order',
		'parent_cid' => $parent_cid,
	);
	
	$ig = new itemGet($params);
	$result = $ig->getResult();
	unset($ig);
	
	$tbk = new tbkDB();
	$tbk->inCategories($result['item_cat']);
	unset($tbk);
	
	foreach ($result['item_cat'] as $cat){
		if ($cat['is_parent'])
			refurbishTaobaoCats($session, $cat['cid']);
	}
	//echo "<br /><span style=\"color:green\">淘宝分类更新完成...</span>...";
}//ENF func refurbishTaobaoCats


/**
 * 获取一组淘宝客商品信息（某个分类或者搜索关键字）
 * @param $session
 * @param $cid
 * @param $sort
 * @return array
 * 
iid 	 String 	 N 	 商品id
title 	String 	N 	商品title 宝贝名称
nick 	String 	N 	卖家昵称
pic_url 	String 	N 	图片url
price 	String 	N 	商品价格
click_url 	String 	N 	推广点击url
commission 	String 	N 	淘宝客佣金
commission_rate 	String 	N 	淘宝客佣金比率
commission_num 	String 	N 	累计成交量
commission_volume 	String 	N 	累计总支出佣金量 
 */
function getTaobaokeItems($session, $params=array('cid' => '16', //cid分类id 默认分类：女装/女士精品
													'keyword' => '雪纺', //keyword关键字，默认： 
													'sort' => 'default',
													'page_size' => 35)){
	$items = array();
	
	/* 用户参数 */
	$p1 = array(  
       'method' => 'taobao.taobaoke.items.get',
       'session'=> $session,
       'fields' => 'iid,title,nick,pic_url,price,click_url,
       		commission,commission_rate,commission_num,commission_volume',
       	'pid' => TAOBAOKE_PID,
		'page_no' => 1, //结果页数.1~99 
		'page_size' => $params['page_size'], //每页返回结果数.最大每页40 
		'sort' => $params['sort'], //默认排序:default , 信用等级从高到低:credit_desc 
								//价格从高到低:price_desc ,价格从低到高:price_asc
		'is_guarantee' => 'true' //是否查询消保卖家 true/false 
	);
	if (!empty($params['cid'])) 
		$p1['cid'] = $params['cid'];
	if (!empty($params['keyword'])) {
		$p1['keyword'] = $params['keyword'];
	}elseif (empty($params['cid']))
		exit("<br /><span style=\"color:red\">getTaobaoItems方法错误!</span>");
	
	$g1 = new itemGet($p1);
	$result = $g1->getResult();
	$items = $result['taobaokeItem'];
	unset($g1);
	return $items;
} //END func getTaobaokeItems

/**
 * 取得单个商品的所在地和属性
 * @param $session
 * @param $nick
 * @param $iid
 * @return array
 * 
iid	商品ID
nick	卖家昵称
cid	商品分类
title	商品标题
location	所在地
properties	属性
 */
function getTaobaoItem($session,$nick,$iid){
	$item = array();
	
	$p1 = array(  
       'method' => 'taobao.item.get',
       'session'=> $session,
		'fields' => 'iid,title,nick,cid,location,props,desc,sku.properties,input_pids,input_str',
		'iid' => $iid,
		'nick' => $nick
	);
	$g1 = new itemGet($p1);
	$result= $g1->getResult();
	$result = $result['item']; //var_dump($result);
	$item['iid'] = $iid;
	$item['nick'] = $nick;
	$item['cid'] = $result['cid'];
	$item['title2'] = $result['title'];
	$item['location'] = $result['location']['state'].'-'.$result['location']['city'];
	$item['desc'] = strip_tags($result['desc']);
	//$pvs = $result['skus']['sku'];
	unset($g1);
	if(empty($item['title2']))
		exit("<br /><span style=\"color:red\">获得单件信息出错！：</span> getTaobaoItem($session,$nick,$iid)");
	
	if(!empty($result['input_str'])) 
		$item['properties'] = $result['input_str']."&nbsp;&nbsp;&nbsp;&nbsp;";
	
	
	if(empty($result['props'])){
		if(empty($item['properties'])) //如果属性为空，则调入随机数
			$item['properties'] = (string)mt_rand(1000,9999999);
		return $item;
	}else
		$pvs = $result['props']; //改版，忽略sku

	$p2 = array(  
		'method' => 'taobao.itempropvalues.get',
	    'session'=> $session,
		'fields' => 'pid,prop_name,name,name_alias',
		'cid' => $item['cid'],
		'pvs' => $pvs
	);
	$g2 = new itemGet($p2);
	$result= $g2->getResult();
	$result = $result[prop_value];
	unset($g2);
	for($i=0; $i<count($result); $i++){
		$item['properties'] .= $result[$i]['prop_name'].':'.$result[$i]['name_alias'].";&nbsp;&nbsp;&nbsp;&nbsp;";
			//.$result[$i]['name'].', '.$result[$i]['name_alias'].";\t\n";
		//if($i%2 == 1) $item['properties'] .= "\t\n";
	}
	
	//$item = $result;
	return $item;
} //END func getTaobaoItem

/**
 * 得到单个淘宝客商铺的信息
 * @param $session
 * @param $nick
 * @return array
 * 
user_id	卖家ID
nick	卖家昵称
credit	卖家信用
sex		卖家性别 m(男),f(女)
sid		店铺ID
title	店铺标题
desc	店铺描述
created	开店时间
click_url	店铺推广URL
shop_commission.rate	佣金比率
 */
function getTaobaokeShop($session,$nick){
	$item = array();
	
	/*   用户     */
	$p1 = array(  
       'method' => 'taobao.user.get',
       'session'=> $session,
       'fields' => 'user_id,nick,sex,seller_credit,created',
       'nick' => $nick
	);
	$g1 = new itemGet($p1);
	$result = $g1->getResult();
	$result = $result['user'];
	
	$item['user_id'] = $result['user_id'];
	$item['nick'] = $result['nick'];
	$item['credit'] = $result['seller_credit']['level'];
	if(empty($result['sex'])) $item['sex'] = 'm'; //m(男),f(女)
	else $item['sex'] = $result['sex'];
	unset($g1);
	if(empty($item['user_id']))
		exit("<br /><span style=\"color:red\">获得商铺<用户>信息出错！：</span> getTaobaokeShop($session,$nick)");
	
	
	/*   店铺     */
	$p2 = array(  
       'method' => 'taobao.shop.get',
       'session'=> $session,
       'fields' => 'sid,cid,nick,title,desc,created ',
       'nick' => $nick
	);
	$g2 = new itemGet($p2);
	$result = $g2->getResult();
	$result = $result['shop'];
	
	$item['sid'] = $result['sid'];
	$item['title'] = $result['title'];
	$item['desc'] = strip_tags($result['desc']);
	$item['created'] = $result['created'];
	unset($g2);
	if(empty($item['sid']))
		exit("<br /><span style=\"color:red\">获得商铺<店铺>信息出错！：</span> getTaobaokeShop($session,$nick)");
	
	if(utf8_strlen($item['desc'])>250){
		$item['desc'] = utf8_trim(substr($item['desc'],0,245)).'...';
	}
	
	/*   链接     */
	$p3 = array(  
       'method' => 'taobao.taobaoke.shops.convert',
       'session'=> $session,
       'fields' => 'user_id,shop_title,click_url,shop_commission.rate',
       'sids' => $item['sid'],
       'nick' => TAOBAOKE_NICK
	);
	$g3 = new itemGet($p3);
	$result = $g3->getResult();
	$result = $result['taobaokeShop'];
	
	$item['click_url'] = $result['click_url'];
	$item['shop_commission.rate'] = $result['shop_commission.rate'];
	unset($g3);
	if(empty($item['click_url']))
		exit("<br /><span style=\"color:red\">获得商铺<链接>信息出错！：</span> getTaobaokeShop($session,$nick)");
		
	return $item;
}//END func getTaobaokeShop



/**
 * 通过商品 标题、属性、分类名 提取关键字
 * 
 * @param String $title 标题
 * @param String $properties 属性
 * @param String $cname 分类名
 * @return Array
 *
 */
function getKeywords($title, $properties, $cname){
	$exclude = array('其它', '品牌', '颜色', '其他品牌', '价格区间', '其它图案',
			 '化妆品规格', '正常规格', '其它材质', '风格', '材质', '款式', '其它形状/图案',
			'女', 'other/其它品牌', '其他风格', '型号', '其它领子', '男', '产品' ,'其它主题',
			'其它品牌内衣', '形状', '其他', '规格', '类型', '适用空间', '其它/other',
			'其它彩妆', '其它品牌', '外贸及其它','更多其它品牌', '其他地方', '其他区域');
	
	$keywords = array();
	$key1 = array();
	$key2 = preg_split('/&nbsp;|:|;/', $properties,  -1, PREG_SPLIT_NO_EMPTY);
	preg_match('/.*<span class=H>(.*)<\/span>.*/', $title, $key1, PREG_OFFSET_CAPTURE);
	
	if(!empty($key1)) array_unshift($keywords, $key1[1][0]);
	for ($i=1; $i<count($key2); $i += 2){
		if ( !in_array( $key2[$i], $exclude) )
			array_push($keywords, $key2[$i]);
	}
	$j = count($keywords) - 5;
	if($j>0){
		for ($i=0; $i<$j; $i++)
			array_pop($keywords);
	}
	array_push($keywords, $cname);
	
	//$step1 = array ("(", ")", "[", "]", "?", "/", "|", "\$", "*", "+", "^", "{", "}" );
	//return str_replace ( $step1, ",", implode(',', $keywords) );
	return $keywords;
} //END func getKeywords

/**
 * 通过商品 第二标题、价格、描述 来获得摘要
 *
 * @param String $title2 第二标题
 * @param String $price 价格
 * @param String $desc 描述
 * @return String
 */
function getExcerpt($title2, $price, $desc){
	$ex = preg_split('/\s|：|，|；|（|）|(&nbsp;)/', $title2.' '.$desc, -1, PREG_SPLIT_NO_EMPTY);
	$ex = array_unique($ex); //去除重复关键字
	$mt_excerpt = implode(' ', $ex); //合并
	$mt_excerpt = $price.'元的'.$mt_excerpt;
	if (utf8_strlen($mt_excerpt) > 110)
		$mt_excerpt = utf8_trim(substr($mt_excerpt,0,220));
	return $mt_excerpt;
} //END func getExcerpt

/**
 * 得到Post主体信息
 *
 * @param Array $item
 * @param Array $keywords
 * @return String
 */
function getContent($item, $keywords){
	$pic_alt = implode(' ', $keywords);
	$credit = getCredit($item['shop_credit']);
	if ($item['shop_sex'] == 'f'){
		$sex = "MM 美眉";
	}else{
		$sex = "GG 帅哥";
	}
	
	$content = "<div class=\"pall\"><div class=\"ppic\">"
			."<a class=\"tbkTooltip\" title=\"{$item['title2']}\" href=\"{$item['click_url']}\">"
			."<img id=\"tbkPic\" onload=\"DrawImg(220,230);\" src=\"{$item['pic_url']}\" alt=\"{$pic_alt}\" />"
			."</a></div><div class=\"pright\"><div class=\"pname\">"
			."<h1>{$item['title2']}</h1><div class=\"right\">卖家信用: {$credit['level']}<br />"
			."<img src=\"{$credit['pic']}\" /></div></div>"
			."<div class=\"pmoney\">淘宝价： <strong>{$item['price']}</strong>元  <span>(此宝贝已参加消费者保障计划)</span>"
			."<div>卖家: {$item['nick']} (宝贝所在地: {$item['location']})</div></div>"
			."<div id=\"tbkBuy\"><p>购买 或 了解宝贝详情，请点击下面的按钮。</p>"
			."<a href=\"{$item['click_url']}\" title=\"立即前往淘宝网购买\"><button> </button></a>"
			."</div></div></div><div class=\"pinfoshow\">"
			."<span>商品属性:</span><div>{$item['properties']}</div></div>"
			."<div id=\"adsSingleMiddle\">"
			."<!--adsense-->"
			."</div><div id=\"tbkShop\"><span>宝贝相关信息:</span>"
			."<p>店铺: <a href=\"{$item['shop_click_url']}\" title=\"{$item['shop_title']}\">{$item['shop_title']}</a></p>"
			."<p>店主: {$item['nick']}({$sex}) 于 {$item['shop_created']} 成为淘宝卖家。</p>"
			."<p>店铺描述: {$item['shop_desc']}</p><span id=\"tbkDescShow\">商品描述: (点击显示/隐藏)</span>"
			."<div id=\"tbkDesc\">{$item['desc']}</div></div>";

	return $content;	
}//END func getContent

/**
 * 得到卖家信用 和 信用图标
 *
 * @param String $credit
 * @return Array
 */
function getCredit($credit){
	if (empty($credit)) return null;
	$c = (int)$credit;
	$num = $c%5;
	if ($num == 0 and $c != 0) $num = 5;
	
	$suffix = intval($c/5);
	//echo 'num = '.$num.'<br />suffix = '.$suffix;
	if ($num > 0 and $num < 5) $suffix += 1;
	
	$pic = "http://pics.taobaocdn.com/newrank/";
	$level = $num;
	
	switch ($suffix) {
    	case 1:
        	$level .= '心';
        	$pic .= 's_red_'.$num.'.gif';
        	break;
    	case 2:
    		$level .= '钻';
    		$pic .= 'b_blue_'.$num.'.gif';
    		break;
    	case 3:
    		$level .= '皇冠';
    		$pic .= 's_cap_'.$num.'.gif';
        	break;
        case 4:
    		$level .= '金冠';
    		$pic .= 's_crown_'.$num.'.gif';
        	break;
	}

	return array('credit' => $credit ,'level' => $level, 'pic' => $pic);
}//END func getCredit

/**
 * 去除首尾空白,乱码
 * 以下函数来自Wordpress中文工具箱 
 * http://yanfeng.org/blog/wordpress/kit
 *
 * @param String $str
 * @return String
 */
function utf8_trim($str) {
//	$len = strlen($str);
	for ($i=strlen($str)-1; $i>=0; $i-=1){
		$hex .= ' '.ord($str[$i]);
		$ch = ord($str[$i]);
        if (($ch & 128)==0) return(substr($str,0,$i));
		if (($ch & 192)==192) return(substr($str,0,$i));
	}
	return($str.$hex);
} //END func utf8_trim

/**
 * 说明：计算 UTF-8 字符串长度（忽略字节的方案）
 * 整理：http://www.CodeBit.cn 
 *
 * @param String $str
 * @return int
 */
function utf8_strlen($str) {
	$i = 0;
	$count = 0;
	$len = strlen ($str);
	while ($i < $len){
		$chr = ord ($str[$i]);
		$count++;
		$i++;
		if($i >= $len) break;
		if($chr & 0x80) {
			$chr <<= 1;
			while ($chr & 0x80) {
				$i++;
				$chr <<= 1;
			}
		}
	}
	return $count;
} //END func utf8_strlen

/**
 * 在线Google翻译,关键字to英文or拼音
 *
 * @param String $text
 * @return String
 */
function change2en($text){
	$snoopy = new Snoopy;
	$url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=".urlencode($text)."&langpair=zh-CN%7Cen";
	$submit_vars["text"] = $text;
	$submit_vars["ie"] = "UTF8"; 
	$submit_vars["hl"] = "zh-CN"; 
	$submit_vars["langpair"] = "zh|en"; 
	$snoopy->submit($url,$submit_vars);
	$htmlret = $snoopy->results;
	$htmlret = explode('translatedText',$htmlret);
	$htmlret = explode('}',$htmlret[1]);
	$htmlret = $htmlret[0];
	$htmlret = str_replace('"','',$htmlret);
	$htmlret = str_replace(':','',$htmlret);
	
	//echo "|{$text}|{$htmlret}|<br />";
	if (empty($htmlret) or $htmlret == $text){ //如果结果为空 或者 没有翻译
		require_once 'pinyin.php';
		$htmlret =  get_pinyin_array($text);
	}
	$htmlret = trim($htmlret);
	return strtolower($htmlret);
} //END func title2plug


function change2pinyin($text){
	require_once 'pinyin.php';
	$htmlret =  get_pinyin_array($text);
	$htmlret = trim($htmlret);
	return strtolower($htmlret);
}

//FILE END
?>